package com.handpay.zztong.hp.onlineshop.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.MD5;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.notification.model.MerchantInfo;
import com.handpay.zztong.hp.onlineshop.model.JieAnConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.utils.AccountUtils;

import java.util.Date;
import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

public class JieAnHtmlActivity extends ZZTongActivity {

    private WebView jieAnWebView;
    private ProgressBar progressBar;
    private String indexurl;
    public static final String ShowHtml_Html_Path_Key = "ShowHtml_Html_Path_Key";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_jie_an_html);
        super.onCreate(savedInstanceState);
        initView();
        getMerchantInfo();
        jieAnWebView.getSettings().setJavaScriptEnabled(true);
        jieAnWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                if (progressBar != null)
                    progressBar.setVisibility(View.INVISIBLE);
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        indexurl = getIntent().getStringExtra(ShowHtml_Html_Path_Key);
    }

    @Override
    protected boolean isShownTabs() {
        return false;
    }

    @Override
    protected boolean isShownTopBar() {
        return true;
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(this.getString(R.string.jiean_title), true);
    }

    private void initView() {
        jieAnWebView = (WebView) findViewById(R.id.jieAnWebView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
    }

    /***
     * 获取当前账户详情
     */
    private void getMerchantInfo() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(this), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, ZZTongActivity.newBankFlag);
        doJsonPost(this, ZZTongActivity.DO_zztGetMerchantInfo, MerchantInfo.class, params);
    }

    /**
     * 外部接入访问统计
     */
    private void getRecordUserVisit() {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put("merchantCode", SecureManager.getInstance().des(AccountUtils.getMerchantCode(this), 1, null));
        params.put("businessType", "02");
        params.put("userInfo", SecureManager.getInstance().des(AccountUtils.getAccountPhone(this) + "|" + AccountUtils.getUserCardNo(this), 1, null));
        doJsonPost(true, this, ZZTongActivity.Do_RecordUserVisit, ResponseBean.class, params, false);
    }

    /**
     * 加载捷安网页
     */
    private void loadJieAnWebView() {
        String suid = AccountUtils.getUserId(this);
        String stimestamp = CommonUtils.getTimestamp(new Date(), "yyyyMMddHHmmss");
        String stoken = new MD5().getMD5ofStr(JieAnConstant.SID + stimestamp + JieAnConstant.SECRETKEY);
        String targetUrl = indexurl + "?sid=" + JieAnConstant.SID + "&suid=" + suid + "&stimestamp=" + stimestamp + "&stoken=" + stoken.toLowerCase();
        HPLog.d(HPLog.SSX_TAG, "targetUrl:" + targetUrl);
        jieAnWebView.loadUrl(targetUrl);
    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
        if (super.netJsonResponse(action, resp, showAlert)) return true;
        if (action.equals(ZZTongActivity.DO_zztGetMerchantInfo)) {
            MerchantInfo merchInfo = (MerchantInfo) resp;
            String phone = merchInfo.getPhone();
            phone = SecureManager.getInstance().des(phone, 0, null);
            String name = merchInfo.getName();
            name = SecureManager.getInstance().des(name, 0, null);
            String certNo = merchInfo.getCertNo();
            certNo = SecureManager.getInstance().des(certNo, 0, null);
            String cardNum = merchInfo.getCardNum();
            cardNum = SecureManager.getInstance().des(cardNum, 0, null);
            AccountUtils.setAccountPhone(this, phone);
            AccountUtils.saveUserName(this, name);
            AccountUtils.saveUsercertNo(this, certNo);
            AccountUtils.saveUserCardNo(this, cardNum);
            getRecordUserVisit();
            loadJieAnWebView();
        } else if (action.equals(ZZTongActivity.Do_RecordUserVisit)) {
            HPLog.d(HPLog.SSX_TAG, "Do_RecordUserVisit");
        }
        return false;
    }


    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        if (super.netResponse(action, resp, showAlert)) {
            return true;
        } else if (action.equals(ZZTongActivity.DO_zztGetMerchantInfo)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            if (luaTable != null) {
                String phone = (String) luaTable.rawget("phone");
                phone = SecureManager.getInstance().des(phone, 0, null);
                String name = (String) luaTable.rawget("name");
                name = SecureManager.getInstance().des(name, 0, null);
                String certNo = (String) luaTable.rawget("certNo");
                certNo = SecureManager.getInstance().des(certNo, 0, null);
                String cardNum = (String) luaTable.rawget("cardNum");
                cardNum = SecureManager.getInstance().des(cardNum, 0, null);
                AccountUtils.setAccountPhone(this, phone);
                AccountUtils.saveUserName(this, name);
                AccountUtils.saveUsercertNo(this, certNo);
                AccountUtils.saveUserCardNo(this, cardNum);
                getRecordUserVisit();
                loadJieAnWebView();
            } else {
                showAlertDialog(this, getString(R.string.tip), "数据加载异常，请重新尝试！", false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        goBack();
                        dialog.dismiss();
                    }
                });
            }
        } else if (action.equals(ZZTongActivity.Do_RecordUserVisit)) {
            HPLog.i(HPLog.YL_TAG, "Do_RecordUserVisit:");
        }
        return false;
    }
}